package cn.lanqiao.springboot.filter;//package cn.lanqiao.rabc.filter;
//
//
//import cn.lanqiao.rabc.util.Result;
//import cn.lanqiao.rabc.vo.UserVO;
//import com.auth0.jwt.JWT;
//import com.auth0.jwt.JWTVerifier;
//import com.auth0.jwt.algorithms.Algorithm;
//import com.auth0.jwt.exceptions.JWTDecodeException;
//import com.auth0.jwt.exceptions.SignatureVerificationException;
//import com.auth0.jwt.exceptions.TokenExpiredException;
//import com.auth0.jwt.interfaces.DecodedJWT;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.core.annotation.Order;
//
//import javax.servlet.*;
//import javax.servlet.annotation.WebFilter;
//import javax.servlet.annotation.WebInitParam;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.util.Arrays;
//import java.util.List;
//
//@Slf4j
//@Configuration
//@Order(2)
//@WebFilter(filterName = "a", urlPatterns = "/*")
//public class LoginFilter implements Filter {
//
//
//
//    @Override
//    public void init(FilterConfig filterConfig) throws ServletException {
//    }
//
//    @Override
//    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        //前置操作
//        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//
//        // 检查请求的URL是否在排除列表中
//        String path = "/user/login,/user/register";
//         List<String> excludedUrls = Arrays.asList(path.split(","));
//        if (excludedUrls.contains(request.getRequestURI())) {
//            filterChain.doFilter(servletRequest, servletResponse); // 不拦截，继续请求
//            return;
//        }
//
//        log.info(request.getMethod());
//
//        try {
//            //获得token操作
//            String token = request.getHeader("Authorization");
//            if (token == null) {
//                failResult(2003, "请先登录！！", response);
//                return;
//            }
//            //解密操作
//            Algorithm algorithm = Algorithm.HMAC256("king");//设置加密方式
//            JWTVerifier jwtVerifier = JWT.require(algorithm).build();//创建认证对象，创建失败会抛出AlgorithmMismatchException异常。
//            DecodedJWT decodedJWT = jwtVerifier.verify(token.substring(7));//对去掉头信息的token进行验证
//            //后续操作
//            UserVO user = new UserVO();
//            user.setUserId(decodedJWT.getClaim("userId").asInt());//获得JWT中的用户id
//            user.setUserName(decodedJWT.getClaim("userName").asString());//获得JWT中的用户名
//            user.setRoleName(decodedJWT.getClaim("roleName").asString());//获得JWT中的角色
//            System.out.println(user);
//
//        } catch (JWTDecodeException e) {
//            failResult(2004, "秘钥格式错误！", response);
//            return;
//        } catch (SignatureVerificationException e) {
//            failResult(2005, "秘钥解密错误！", response);
//            return;
//        } catch (TokenExpiredException e) {
//           failResult(2006, "token过期，请重新登录！", response);
//           return;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        filterChain.doFilter(servletRequest, servletResponse);
//        //后置操作
//    }
//
//    /**
//     * 验证失败统一向前端返回错误结果
//     *
//     * @param code     错误码
//     * @param message  错误信息
//     * @param response 响应对象
//     */
//    public boolean failResult(int code, String message, HttpServletResponse response) {
//        try {
//            ObjectMapper objectMapper = new ObjectMapper();//使用jackson，也可以使用fastjson
//            response.setContentType("text/html;charset=UTF-8");
//            response.getWriter().print(objectMapper.writeValueAsString(Result.error(code, message)));
//            response.flushBuffer();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return false;
//    }
//
//    @Override
//    public void destroy() {
//        Filter.super.destroy();
//    }
//}
